import React, { useEffect, useState } from "react";
import { Descriptions } from "antd";
import { HeartTwoTone } from "@ant-design/icons";
import { useParams } from "react-router";
import { PageHeader } from "@ant-design/pro-layout";
import moment from "moment";
import axios from "axios";
export default function Detail() {
  const [newsInfo, setNewsInfo] = useState(null);
  const params = useParams();
  useEffect(() => {
    axios
      .get(`/news/${params.id}?_expand=category&_expand=role`)
      .then((res) => {
        if (res.data.label) {
          res.data.title = res.data.label;
        }
        //    每次进入该页面都会增加一次浏览量，所以直接把请求回来的数据进行处理
        setNewsInfo({
          ...res.data, //当前新闻的详细信息
          view: res.data.view + 1, //访问量
        });
        // 同步后端
        return res.data;
      })
      .then((res) => {
        axios.patch(`/news/${params.id}`, {
          view: res.view + 1, //这的res是上面return出来的
        });
      });
  }, [params.id]);

  // 点赞
  const handleStar = () => {
    // 更改本地状态
    setNewsInfo({
      ...newsInfo,
      star: newsInfo.star + 1,
    });
    // 同步后端
    axios.patch(`/news/${params.id}`, {
      star: newsInfo.star + 1, //这的res是上面return出来的
    });
  };
  return (
    <div>
      {newsInfo && (
        <PageHeader
          onBack={() => window.history.back()}
          title={newsInfo.title}
          subTitle={
            // 小红心
            <div>
              {newsInfo.category.label}
              <HeartTwoTone twoToneColor="#eb2f96" onClick={handleStar} />
            </div>
          }
        >
          <Descriptions size="small" column={3}>
            <Descriptions.Item label="创建者">
              {newsInfo.author}
            </Descriptions.Item>
            <Descriptions.Item label="发布状态">
              {newsInfo.publishTime
                ? moment(newsInfo.createTime).format("YYYY/MM/DD HH:mm:ss")
                : "-"}
            </Descriptions.Item>
            <Descriptions.Item label="区域">
              {newsInfo.region}
            </Descriptions.Item>
            <Descriptions.Item label="访问数量">
              <span style={{ color: "green" }}>{newsInfo.view}</span>
            </Descriptions.Item>
            <Descriptions.Item label="点赞数量">
              <sapn style={{ color: "green" }}>{newsInfo.star}</sapn>
            </Descriptions.Item>
            <Descriptions.Item label="评论数量">
              <sapn style={{ color: "#f0f" }}>{newsInfo.star}</sapn>
            </Descriptions.Item>
          </Descriptions>
        </PageHeader>
      )}
      <div
        dangerouslySetInnerHTML={{ __html: newsInfo?.content }}
        style={{ border: "1px solid #ccc", padding: "24px", margin: "20px" }}
      ></div>
    </div>
  );
}
